import datetime
import time

from flask import Flask
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask_cors import CORS

import rsa
import sqlhelper

app = Flask(__name__, static_url_path='')


@app.route('/',methods=['GET'])
def realIndex():
    return render_template('homepage.html')


@app.route('/table/<id>', methods=['GET', 'POST'])
def index(id):
    # 接收易杭商传过来的值
    try:
        data = request.args.get('data')  # 这里以后测试完成改回form获取参数
        user = rsa.getEncyptedData(data)
        print(user)
    except Exception:
        return app.send_static_file('noperssion.html')

    conn, cur = sqlhelper.create_conn()
    try:
        id = int(id)  # 防止恶意注入
    except Exception:
        return "error"
    res = sqlhelper.fetch_all("select * from vtable where id=%s" % (id))
    print(res)
    if (res != None and res[0] != None):
        sqlhelper.close_conn(conn, cur)
        print(res[0]['context'])
        return render_template("index.html", content=res[0]['context'], code=data, table_id=res[0]['id'])
        # return render_template("index.html", content=res[0]['context'],code=data,table_id=id)
    sqlhelper.close_conn(conn, cur)
    return "error"


@app.route('/editor/')
def editor():
    return render_template('editor.html')


@app.route('/editor/<id>')
def resave(id=0):
    if id != 0 or id != "":
        return render_template('editor.html')
    else:
        return redirect(302, "./editor")


@app.route('/getsurvey', methods=['POST', 'GET'])
def getsurvey():
    if request.method == 'POST':
        surveyId = request.form.get("id")
        conn, cur = sqlhelper.create_conn()
        res = sqlhelper.fetch_one("select * from vtable where id=%s", (surveyId))
        print(res)
        content=res["context"]
        sqlhelper.close_conn(conn, cur)
        return jsonify({"code": 200, "message": "提交成功!", "survey": content})
    elif request.method == 'GET':
        surveyId = request.args.get("id")
        conn, cur = sqlhelper.create_conn()
        res = sqlhelper.fetch_one("select * from vtable where id=%s", (surveyId))
        print(res)
        content = res["context"]
        sqlhelper.close_conn(conn, cur)
        return jsonify({"code": 200, "message": "提交成功!", "survey": content})


@app.route('/submit', methods=['POST'])
def get_vote():
    code = request.form['code']
    table_id = int(request.form['table_id'])
    data = request.form['data']
    # try:
    user = rsa.getEncyptedData(code)
    # {"yb_classname":"计科18C","yb_collegename":"理工分院","yb_employid":"","yb_realname":"洪德衍","yb_studentid":"1841920344","yb_userid":"18884862"}
    conn, cur = sqlhelper.create_conn()

    table_edate = sqlhelper.fetch_one("select edate,sdate from vtable where id=%s", (table_id))
    # 判断截止时间
    # print(table_edate)
    if (table_edate == None):
        sqlhelper.close_conn(conn, cur)
        return {"code": 500, "message": "数据错误!"}
    datetime_now = datetime.datetime.now()
    edate = table_edate['edate']
    sdate = table_edate['sdate']
    # 判断截止时间和开始时间
    if time.mktime(datetime_now.timetuple()) - time.mktime(sdate.timetuple()) < 0:
        sqlhelper.close_conn(conn, cur)
        return {"code": 500, "message": "还未到开始时间!"}
    # print(datetime_now)
    if time.mktime(datetime_now.timetuple()) - time.mktime(edate.timetuple()) > 0:
        sqlhelper.close_conn(conn, cur)
        return {"code": 500, "message": "已经超过截止时间时间!"}

    user = eval(user)
    # 判断当前用户的投票是否已经存在
    exist = sqlhelper.fetch_one("select * from votes where table_id=%s and yb_userid=%s", (table_id, user['yb_userid']))
    if (exist == None):
        vote_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        yb_employid = user['yb_employid']
        # 防止出现教师和学生的id为空的情况
        if yb_employid == '':
            yb_employid = None
        yb_userid = user['yb_userid']
        if yb_userid == '':
            yb_userid = None
        sqlhelper.insert(
            "insert into votes(yb_userid,vote_time,table_id,data,yb_classname,yb_collegename,yb_employid,yb_realname) values (%s,%s,%s,%s,%s,%s,%s,%s)",
            (
                yb_userid, vote_time, table_id, data, user['yb_classname'], user['yb_collegename'], yb_employid,
                user['yb_realname']
            ))
        sqlhelper.close_conn(conn, cur)
        return {"code": 200, "message": "提交成功!"}
    else:
        return {"code": 500, "message": "重复提交!"}
    sqlhelper.close_conn(conn, cur)
    return data


@app.route("/newsurvey", methods=["POST", "GET"])
def newSurvey():
    content = (request.form["content"])
    content_list = eval(content)
    if "title" not in content_list["pages"][0] or str(content_list["pages"][0]["title"]).strip()=="":
        return jsonify({"code": 301, "message": "您未填写问卷标题"})
    if content != "":
        print(content_list)
        conn, cur = sqlhelper.create_conn()
        defaultTime="1970-01-01 00:00:00"
        # 这里默认时间和日期都是1970年，后期来进行修改
        sqlhelper.insert('''insert into vtable (name,cdate,edate,context,sdate) values (%s,%s,%s,%s,%s)''',(str(content_list["pages"][0]["title"]),defaultTime,defaultTime,str(content_list),str(datetime.datetime.now())))
        sqlhelper.close_conn(conn,cur)
        return jsonify({"code": 200, "message": "试题保存成功!请前往管理页面设置考试的起止时间"})
    else:
        return jsonify({"code": 301, "message": "保存失败，请检查"})

    #Todo:这里，你需要写一个解析文件的方法，并保存
@app.route("/import",methods=["POST"])
def importPapers():
    '''
    todo:1、判断导入的内容是什么文件格式，对应不同的解析方式
    2、按照文件的格式解析完后，生成对应的字典
    3、生成的试卷要能够进行预览
    

    :return:
    '''
    pass

@app.route("/importer")
def imp():
    return render_template("./importor.html")


CORS(app, resources=r'/*', supports_credentials=True)

if __name__ == '__main__':
    app.run(debug=True, host="127.0.0.1")
